package com.cedifie.lendapp.ui.steps.act

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.text.TextUtils
import android.view.Gravity
import android.view.View
import com.cedifie.http.model.Progress
import com.cedifie.lendapp.R
import com.cedifie.lendapp.databinding.ActOcrUploadBinding
import com.cedifie.lendapp.http.HttpHelper
import com.cedifie.lendapp.ui.steps.impl.CedUploadPresenterImpl
import com.cedifie.lendapp.ui.steps.view.ICedUploadView
import com.cedifie.lendapp.ui.user.act.CedUserFeedbackAct
import com.cedifie.lendapp.utils.event.CedEventData
import com.cedifie.lendapp.utils.event.CedEventType
import com.cedifie.lendapp.mvp.MvpAct
import com.lib.base.utils.ImageUtil
import com.lib.base.utils.helper.ActivityStackManager
import org.greenrobot.eventbus.EventBus
import org.json.JSONObject
import java.io.File

/**
 * Cedifie
 * @Author wwdeng
 * @CreateTime: 2024/6/21 11:59
 * @Annotation：驾驶证、护照、身份证拍照 上传
 */
class CedOcrUploadAct: MvpAct<ICedUploadView, CedUploadPresenterImpl>(),ICedUploadView {
    lateinit var binding: ActOcrUploadBinding

    //上传完成的图片地址
    var imgUrl = ""

    companion object {
        //类型 ： PASSPORT、IDCARD、DRIVING
        private const val INTENT_KEY_TYPE = "ocrType"
        private const val INTENT_KEY_IMG_PATH = "imgPath"
        fun start(context: Context,ocrType: String, imgPath: String?) {
            if (TextUtils.isEmpty(imgPath)) {
                return
            }
            val intent = Intent(context, CedOcrUploadAct::class.java)
            intent.putExtra(INTENT_KEY_TYPE, ocrType)
            intent.putExtra(INTENT_KEY_IMG_PATH, imgPath)
            context.startActivity(intent)
        }
    }

    override fun getCedRootView(): View {
        binding = ActOcrUploadBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun createMvpPresenter(): CedUploadPresenterImpl {
        return CedUploadPresenterImpl(this)
    }

    override fun initCedView() {
        setCedTitleBarVisibility(View.VISIBLE)
        setCedTextTitle(getString(R.string.process_ocr_uploading))
        setCedTextTitleGravity(Gravity.CENTER)
    }

    override fun initCedListener() {
        //联系客服
        rootViewBinding.ivFun.setOnClickListener {
            onIntent(CedUserFeedbackAct::class.java)
            HttpHelper.addCedEventAction(CedEventType.CLICK.CED_CLICK_CUSTOMER,"OcrUpload ${getCedOrcType()} Page")
        }

        //使用照片
        binding.btnUsePhoto.setOnClickListener {
            HttpHelper.addCedEventAction(CedEventType.CLICK.CED_CLICK_STEP_OCR_UPLOAD_USE_PHOTO, "${getCedOrcType()}：$imgUrl")
            //关闭拍照页面
            ActivityStackManager.finishActivity(CedCameraOcrAct::class.java)

            val data = JSONObject()
            data.put("imgUrl",imgUrl)
            data.put("imgPath",getCedImgPath())
            EventBus.getDefault().post(CedEventData(CedEventData.TYPE.CED_USE_PHOTO,data))
            finish()
        }

        //重新获取
        binding.btnRetake.setOnClickListener {
            HttpHelper.addCedEventAction(CedEventType.CLICK.CED_CLICK_STEP_OCR_UPLOAD_RETAKE, "${getCedOrcType()}：$imgUrl")
            val file = File(getCedImgPath())
            if (file.isFile){
                file.delete()
            }
            setResult(RESULT_OK)
            finish()
        }

        //重新上传
        binding.btnAgain.setOnClickListener {
            //显示上传中状态
            showUploadingView()
            showCedLoading(isTOuchOut = false, isCancel = true,getString(R.string.loading))
            mvpPresenter?.onCedUploadImageAction(getCedImgPath())
        }
    }

    override fun initCedData() {
        ImageUtil.instance?.loadImageUrl(this,binding.imgView,getCedImgPath())

        //显示上传中状态
        showUploadingView()
        showCedLoading(isTOuchOut = false, isCancel = true,getString(R.string.loading))
        mvpPresenter?.onCedUploadImageAction(getCedImgPath())
    }

    /**
     * 上传中状态
     */
    private fun showUploadingView(){
        binding.btnAgain.visibility = View.GONE
        binding.textProgress.visibility = View.VISIBLE
        binding.imgComplete.visibility = View.GONE
        binding.btnRetake.alpha = 0.5f
        binding.btnRetake.isEnabled = false
        binding.btnUsePhoto.alpha = 0.5f
        binding.btnUsePhoto.isEnabled = false

        binding.progressBar.max = 100
        binding.progressBar.progress = 0
        binding.textProgress.text = "0%"
    }

    /**
     * 上传进度回调
     */
    @SuppressLint("SetTextI18n")
    override fun showCedUploadProgress(totalSize: Long, currentSize: Long) {
        binding.progressBar.max = totalSize.toInt()
        binding.progressBar.progress = currentSize.toInt()
        binding.textProgress.text = ((currentSize / totalSize) * 100).toString()+"%"
    }

    /**
     * 上传完成
     */
    override fun showCedUploadSuccess(imgUrl: String) {
        this.imgUrl = imgUrl
        binding.btnAgain.visibility = View.GONE
        binding.textProgress.visibility = View.GONE
        binding.imgComplete.visibility = View.VISIBLE
        binding.btnRetake.alpha = 1f
        binding.btnRetake.isEnabled = true
        binding.btnUsePhoto.alpha = 1f
        binding.btnUsePhoto.isEnabled = true
    }

    /**
     * 上传失败
     */
    override fun showCedUploadFailed() {
        binding.btnAgain.visibility = View.VISIBLE
        binding.textProgress.visibility = View.VISIBLE
        binding.imgComplete.visibility = View.GONE
        binding.btnRetake.alpha = 0.5f
        binding.btnRetake.isEnabled = false
        binding.btnUsePhoto.alpha = 0.5f
        binding.btnUsePhoto.isEnabled = false

        binding.progressBar.max = 100
        binding.progressBar.progress = 0
        binding.textProgress.text = "0%"
    }

    /**
     * 获取Ocr类型
     *  PASSPORT、IDCARD、DRIVING
     */
    private fun getCedOrcType(): String{
        intent.extras?.let {
            return it.getString(INTENT_KEY_TYPE,"")
        }
        return ""
    }

    /**
     * 获取图片路径
     */
    private fun getCedImgPath(): String{
        intent.extras?.let {
            return it.getString(INTENT_KEY_IMG_PATH,"")
        }
       return ""
    }

    override fun onStart() {
        super.onStart()
        HttpHelper.addCedEventAction(CedEventType.PAGE.CED_PAGE_STEP_OCR_UPLOAD_START,getCedOrcType())
    }

    override fun onDestroy() {
        super.onDestroy()
        HttpHelper.addCedEventAction(CedEventType.PAGE.CED_PAGE_STEP_OCR_UPLOAD_END,getCedOrcType())
    }
}